package com.bw.controller;

import com.alibaba.fastjson2.JSON;
import com.bw.domain.Pj;
import com.bw.domain.Role;
import com.bw.domain.TbMenu;
import com.bw.domain.User;
import com.bw.service.RoleService;
import com.bw.utils.MenuUtil;
import com.bw.utils.R;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;

/**
 * @Author: Wrj
 * @Date: 2025/3/9 10:06
 * @Description:
 **/
@Controller
@RequestMapping("role")
public class RoleController {
    @Autowired
    RoleService roleService;



    @ResponseBody
    @RequestMapping("add")
    public R add(Role role){
        Boolean b=roleService.add(role);

        return b?R.OK():R.ERROR(404,"添加失败");
    }

    /**
     * 检查角色名称是否存在，如果存在则返回该角色用哟的菜单id
     * @param roleName
     * @return
     */
    @ResponseBody
    @RequestMapping("checkRoleName")
    public R checkRoleName(String roleName){
        Role role=roleService.listRole(roleName);
        //如果角色存在则查询角色拥有的权限
        if (role!=null){
            List<Integer> menuIds=roleService.listMenuIdsByRoleName(roleName);
            //分装到map
            HashMap<String, Object> map = new HashMap<>();
            map.put("menuIds",menuIds);
            map.put("roleId",role.getRoleId());

            return R.ERROR(404,"该名称已经重复",map);
        }
        return R.OK();
    }


    /**
     * 跳转到角色添加
     * @param model
     * @return
     */
    @RequestMapping("toadd")
    public String toadd(Model model){
        //查询所有菜单
        List<TbMenu> menuList=roleService.listMenu();
        //转成树形结构
        List<TbMenu> tbMenuList = MenuUtil.treeMenus(menuList, null);
        model.addAttribute("tbMenuList", JSON.toJSON(tbMenuList));
        return "role/add";
    }

    @RequestMapping("tolist")
    public String tolist(){
        return "role/list";
    }

    @ResponseBody
    @RequestMapping("list")
    public R list(Role role,Integer page,Integer limit){
        PageHelper.startPage(page,limit);
        List<Role> roleList=roleService.list(role);
        PageInfo<Role> pageInfo = new PageInfo<>(roleList);
        return R.OK(pageInfo);
    }
}
